package com.windrift.springhibernate.service;

import com.windrift.springhibernate.model.AssetType;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Transactional
@Service("assetTypeService")
public class AssetTypeServiceImpl implements AssetTypeService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<AssetType> findAll() {
        Query query = getEntityManager().createQuery("SELECT a FROM AssetType a WHERE a.parent IS NULL ORDER BY sequence ASC, id DESC");
        return query.getResultList();
    }


    public List<AssetType> findChildren(Integer parentId) {

        Query query = getEntityManager().createQuery("SELECT a FROM AssetType a WHERE a.parent = " + parentId + " ORDER BY sequence ASC, id DESC");
        List<AssetType> items= query.getResultList();
        return items;
    }

    private void save(AssetType assetType) {
        if (assetType.getId() == null) {
            // new
            em.persist(assetType);
        } else {
            // update
            em.merge(assetType);
        }
    }

    public void remove(int id) {
        AssetType assetType = find(id);
        if (assetType != null) {
            em.remove(assetType);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public AssetType find(int id) {
        return em.find(AssetType.class, id);
    }

    public void add(AssetType assetType) {
        this.save(assetType);
    }

    public void update(AssetType assetType) {
        this.save(assetType); 
    }

}
